package company.bytedance

import kotlin.math.abs

fun main(args: Array<String>) {


    val array = arrayOf(1,3,6,7,9,90,98,101,239,778)

    findNearstIndex(array,770)
}


fun findNearstIndex(numbers: Array<Int>, t: Int): Int {


    var r = 0;

    var hi = Int.MAX_VALUE
    var lo = 0

    var left = 0
    var right = numbers.lastIndex
    var mid = (left + right + 1) / 2
    var gap = abs(numbers[mid] - t)
    while (left <= right) {

        val v = numbers[mid]
        val currGap = abs(mid - t)
        if (currGap == 0)
            return mid
        else if (currGap < gap) {
            hi = mid
            gap = currGap
            left = mid + 1
        } else if (currGap > gap) // 此时距离变大了，不需要继续往后找
            break
    }

    left = 0
    right = numbers.size / 2
    gap = abs(numbers[mid] - t)
    mid = (left + right + 1) / 2
    while (left <= right) {

        val v = numbers[mid]
        val currGap = abs(mid - t)
        if (currGap == 0)
            return mid
        else if (currGap < gap) {
            right = mid - 1
            lo = mid

        } else break
    }

    println("${numbers.size} $hi $lo")
    r = if (abs(numbers[hi] - t) < abs(numbers[lo] - t)) hi else lo

    return r
}